package cn.js189.common.util.sign;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.text.CharSequenceUtil;
import cn.js189.common.constants.Constants;
import cn.js189.common.domain.ReqInfo;
import cn.js189.common.util.ServletUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.security.Key;

/**
 * des 解密工具
 */
@Slf4j
public class DesUtils {
	
	private DesUtils(){
		/* empty */
	}
	
	/**
	 * des+base64解密过程
	 */
	public static String getDecString(String strMi, String strKey) {
		byte[] byteMing;
		byte[] byteMi;
		String strMing = "";
		Key key = getKey(strKey);
		byteMi = Base64.decode(strMi);
		byteMing = getDecCode(byteMi, key);
		strMing = new String(byteMing, StandardCharsets.UTF_8);
		return strMing;
	}
	
	/**
	 * des解密
	 */
	private static byte[] getDecCode(byte[] bytes, Key key) {
		byte[] byteFina = null;
		Cipher cipher;
		try {
			cipher = Cipher.getInstance(Constants.DES_STR);
			cipher.init(Cipher.DECRYPT_MODE, key);
			byteFina = cipher.doFinal(bytes);
		} catch (Exception e) {
			log.debug(e.getMessage());
		}
		return byteFina;
	}
	
	/**
	 * 生成des key
	 */
	private static Key getKey(String strKey) {
		Key key = null;
		try {
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(Constants.DES_STR);
			DESKeySpec keySpec = new DESKeySpec(strKey.getBytes());
			key = keyFactory.generateSecret(keySpec);
		} catch (Exception e) {
			log.debug(e.getMessage());
		}
		return key;
	}
	
	/**
	 * body参数des解密
	 * @param reqInfo 请求入参
	 */
	public static JSONObject desBody(JSONObject reqInfo){
		HttpServletRequest request = ServletUtils.getRequest();
		if(request != null){
			String encKey = String.valueOf(request.getAttribute(Constants.DES_BODY_KEY));
			desBody(reqInfo,encKey);
		}
		return reqInfo;
	}
	
	/**
	 * body参数des解密
	 * @param reqInfo 请求入参
	 * @param encKey 密钥
	 */
	public static void desBody(JSONObject reqInfo, String encKey){
		HttpServletRequest request = ServletUtils.getRequest();
		if(request != null && CharSequenceUtil.isNotBlank(encKey)){
			encKey = String.valueOf(request.getAttribute(Constants.DES_BODY_KEY));
		}
		// 外网渠道要进行Body des解密
		if(CharSequenceUtil.isNotBlank(encKey)){
			String reqBodyStr = reqInfo.getString("body");
			try{
				String reqBodyDecStr = DesUtils.getDecString(JSON.toJSONString(reqBodyStr), encKey);
				JSONObject reqBody = JSON.parseObject(reqBodyDecStr);
				reqBody.put(Constants.UQC_ENC_FLAG, "Y");
				reqInfo.put("body",reqBody);
			}catch (Exception e){
				log.error("body参数解密失败,{}",e.getMessage(),e);
			}
		}
	}
	
}
